import Taro, { useDidShow } from '@tarojs/taro';
import {
  Avatar,
  Button,
  Cell,
  CountDown,
  Dialog,
} from '@nutui/nutui-react-taro';
import { View, Text, Image } from '@tarojs/components';
import { IconFont } from '@nutui/icons-react-taro';
import { useEffect, useState } from 'react';
import { generateUUID } from '@/utils/uuid';
import { priceToString } from '@/utils/price';
import {
  DetailPageType,
  EnumOrderStatus,
  getPaidStopTime,
  IOrder,
  IOrderDisplay,
  IOrderTotal,
  orderStatusFormat,
  orderTotalStatusFormat,
} from '@/types/order';
import './card-order.less';
import { cancel } from '@/utils/wxpay';
import { EnumCrowd, EnumTicketType } from '@/types/ticket';
import { formatDate, formatDate2, formatDateTime } from '@/utils/time';

interface IProps {
  orderTotal: IOrder;
  refreshList: () => void;
}

const sortDisplayOrder = (orders: IOrderDisplay[]) => {
  return orders.sort((a, b) => {
    if (a.attribute.crowd === EnumCrowd.ADULT) {
      return -1;
    } else if (b.attribute.crowd === EnumCrowd.ADULT) {
      return 1;
    } else {
      return -9;
    }
  });
};


const goDetailPage = (orderTotalId: string, type: string = 'detail') => {
  Taro.navigateTo({
    url: `/pages/order-detail/index?id=${orderTotalId}&type=${type}`,
  });
};

const goPayPage = (orderTotal: IOrder) => {
  const stopTime = getPaidStopTime(orderTotal.createTime);
  const now = new Date().getTime();
  if (stopTime <= now) {
    goDetailPage(orderTotal.id, DetailPageType.DETAIL);
  } else {
    let url = `/pages/order-review/index?price=${orderTotal.orderAmount}&orderId=${orderTotal?.id}&time=${orderTotal.time}`;
    if (orderTotal.timeEnd) {
      url += `&timeEnd=${orderTotal.timeEnd}`;
    }
    Taro.navigateTo({ url });
  }
};

const buttonsRenderUnPaid = (
  orderTotal: IOrder,
  confirmCancel: (orderTotalId: string) => void
) => {
  const stopTime = new Date(orderTotal.createTime).getTime() + 1000 * 60 * 30;
  const now = new Date().getTime();
  return (
    <View className="buttons-unpaid">
      {now < stopTime ? (
        <View className="stop-time">
          剩余
          <CountDown remainingTime={stopTime - now} />
        </View>
      ) : (
        <View className="out-time"></View>
      )}
      <View style={{ height: 24 }}>
        {now < stopTime && (
          <>
            <Button
              type="primary"
              size="mini"
              onClick={() => goPayPage(orderTotal)}>
              付款
            </Button>
          </>
        )}
        {/* {now >= stopTime && (
          <Button
            type="default"
            size="mini"
            onClick={() => goDetailPage(orderTotal.id)}>
            详情
          </Button>
        )} */}
      </View>
    </View>
  );
};

const goTicketPage = () => {
  Taro.navigateTo({ url: '/pages/ticket-use/index' });
};

const buttonsRenderPaid = () => {
  return null;
  return (
    <>
      <Button type="primary" size="mini" onClick={goTicketPage}>
        使用
      </Button>
    </>
  );
};

const buttonRenderDetail = (orderTotal: IOrder) => {
  return null;
  return (
    <Button
      type="default"
      size="mini"
      onClick={() => goDetailPage(orderTotal.id)}>
      详情
    </Button>
  );
};

const buttonsRender = (
  orderTotal: IOrder,
  confirmCancel: (orderTotalId: string) => void
) => {
  if (orderTotal.status === EnumOrderStatus.UNPAID) {
    return buttonsRenderUnPaid(orderTotal, confirmCancel);
  } else if (orderTotal.status === EnumOrderStatus.PAID) {
    return buttonsRenderPaid();
  } else if (
    orderTotal.status === EnumOrderStatus.REFUNDING ||
    orderTotal.status === EnumOrderStatus.EXCEPTION ||
    orderTotal.status === EnumOrderStatus.CANCELED ||
    orderTotal.status === EnumOrderStatus.REFUNDED ||
    orderTotal.status === EnumOrderStatus.USED
  ) {
    return buttonRenderDetail(orderTotal);
  }
};

const isGoPayPage = (orderTotal: IOrder) => {
  if (orderTotal.status === EnumOrderStatus.UNPAID) {
    return true;
  }
  return false;
};

export default function Index(props: IProps) {
  const { orderTotal, refreshList } = props;

  useDidShow(() => {
    // 确保组件挂载后再进行操作
    try {
      Taro.hideLoading();
    } catch (error) {
      console.error('页面加载错误:', error);
    }
  });

  /**
   * 取消订单
   */
  const initCancel = async (orderId: string) => {
    try {
      await cancel(
        orderId,
        () => {
          Taro.showToast({
            title: `订单取消成功`,
            icon: 'none',
          }).catch(console.error);
          refreshList();
        },
        () => {
          Taro.showToast({
            title: `订单取消失败`,
            icon: 'none',
          }).catch(console.error);
        }
      );
    } catch (error) {
      console.error('取消订单错误:', error);
    }
  };

  const confirmCancel = (orderTotalId: string) => {
    Dialog.open('cancel', {
      title: '取消提醒',
      content: '取消操作无法回退，确定取消吗？',
      onConfirm: () => {
        initCancel(orderTotalId);
        Dialog.close('cancel');
      },
      onCancel: () => {
        Dialog.close('cancel');
      },
    });
  };

  const goToDetail = (e: any) => {
    try {
      e?.stopPropagation();
      if (isGoPayPage(orderTotal)) {
        goPayPage(orderTotal);
      } else {
        goDetailPage(orderTotal.id);
      }
    } catch (error) {
      console.error('页面跳转错误:', error);
    }
  };

  return (
    <View className="order-card-order">
      <Cell.Group>
        <Cell
          className="cell-row-1"
          title={
            <View className="order-title">
              {/* // 2025-03-08T01:45:26.906Z 格式转化成 2025-03-08*/}
              <View>订单时间：{formatDate2(orderTotal?.createTime || '')}</View>
              <View className="status">
                {orderStatusFormat(orderTotal?.status)}
              </View>
            </View>
          }
        />
        <Cell>
          <View className="order-box">
            <View className="icon-box">
              <Avatar
                size="48"
                icon={
                  <IconFont
                    size={22}
                    fontClassName="icon"
                    color="#000"
                    classPrefix="go-farm"
                    name="avatar"
                  />
                }
                shape="round"
              />
            </View>
            <View className="order-item-wrapper">
              <View className="wrapper-title">
                <View>{orderTotal?.orderType === "trash" ? "扔垃圾" : "取快递"}</View>
                <View>{orderTotal.price}</View>
              </View>
              {
                orderTotal.takeNum ? <View className="wrapper-date">
                  快递数量：{orderTotal.takeNum}
                </View> : null
              }
              {
                orderTotal.takeBigNum ? <View className="wrapper-date">
                  其中大件数量：{orderTotal.takeBigNum}
                </View> : null
              }
              {
                orderTotal.desc ? <View className="wrapper-date">
                  {orderTotal.orderType === "parcel" ? "取件码" : "备注"}：{orderTotal.desc}
                </View> : null
              }
              {
                orderTotal.time && <View className="wrapper-date">
                  预约时间：{orderTotal.time}
                </View>
              }
              {
                orderTotal.timeEnd && <View className="wrapper-date">
                  结束时间：{orderTotal.timeEnd}
                </View>
              }
              <View className="wrapper-date">
                地址：{orderTotal.fullAddress}
              </View>
              {orderTotal.imageList && (
                <View className="image-list">
                  {(() => {
                    // 确保imageList是数组
                    const imgList = typeof orderTotal.imageList === 'string' 
                      ? [orderTotal.imageList] 
                      : orderTotal.imageList;
                    
                    return imgList.map((img, index) => (
                      <Image 
                        key={index}
                        src={img} 
                        className="order-image" 
                        mode="aspectFill"
                        onClick={(e) => {
                          e.stopPropagation();
                          Taro.previewImage({
                            current: img,
                            urls: imgList
                          })
                        }}
                      />
                    ));
                  })()}
                </View>
              )}
            </View>
          </View>
        </Cell>
        <Cell className="cell-foot">
          <View className="order-buttons">
            {buttonsRender(orderTotal, confirmCancel)}
          </View>
        </Cell>
      </Cell.Group>
    </View>
  );
}
